{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a2840001",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "%pip install --upgrade --quiet  flashrank\n",
    "%pip install --upgrade --quiet  faiss_cpu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86ecb548",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet langchain-openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8ef7668b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Helper function for printing docs\n",
    "def pretty_print_docs(docs):\n",
    "    print(\n",
    "        f\"\\n{'-' * 100}\\n\".join(\n",
    "            [\n",
    "                f\"Document {i + 1}:\\n\\n{d.page_content}\\nMetadata: {d.metadata}\"\n",
    "                for i, d in enumerate(docs)\n",
    "            ]\n",
    "        )\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b48ab517",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.document_loaders import TextLoader\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\n",
    "documents = TextLoader(\n",
    "    \"./state_of_the_union.txt\", encoding=\"utf-8\"\n",
    ").load()\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)\n",
    "texts = text_splitter.split_documents(documents)\n",
    "for idx, text in enumerate(texts):\n",
    "    text.metadata[\"id\"] = idx\n",
    "\n",
    "embedding = OpenAIEmbeddings(model=\"text-embedding-ada-002\")\n",
    "retriever = FAISS.from_documents(texts, embedding).as_retriever(search_kwargs={\"k\": 20})\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = retriever.invoke(query)\n",
    "pretty_print_docs(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c5fddd08",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:flashrank.Ranker:Downloading ms-marco-MultiBERT-L-12...\n",
      "ms-marco-MultiBERT-L-12.zip: 100%|██████████| 98.7M/98.7M [00:17<00:00, 6.05MiB/s]\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[73, 50, 35]\n"
     ]
    }
   ],
   "source": [
    "from langchain.retrievers import ContextualCompressionRetriever\n",
    "from langchain_community.document_compressors import FlashrankRerank\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI(temperature=0)\n",
    "\n",
    "compressor = FlashrankRerank()\n",
    "compression_retriever = ContextualCompressionRetriever(\n",
    "    base_compressor=compressor, base_retriever=retriever\n",
    ")\n",
    "\n",
    "compressed_docs = compression_retriever.invoke(\n",
    "    \"What did the president say about Ketanji Jackson Brown\"\n",
    ")\n",
    "print([doc.metadata[\"id\"] for doc in compressed_docs])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5c8ed73",
   "metadata": {},
   "outputs": [],
   "source": [
    "pretty_print_docs(compressed_docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f04aba7f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'query': 'What did the president say about Ketanji Brown Jackson',\n",
       " 'result': \"The President mentioned that Ketanji Brown Jackson is one of the nation's top legal minds and will continue Justice Breyer's legacy of excellence.\"}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.chains import RetrievalQA\n",
    "\n",
    "chain = RetrievalQA.from_chain_type(llm=llm, retriever=compression_retriever)\n",
    "chain.invoke(query)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
